package com.irun.pm.ui;

import java.io.File;
import java.util.Calendar;
import java.util.concurrent.Callable;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.irun.pm.R;
import com.irun.pm.controller.DriverInfoControllers;
import com.irun.pm.interfaces.Callback;
import com.irun.pm.mode.DriverInfo;
import com.irun.pm.utils.FileUtils;
import com.irun.pm.utils.ImageUtil;
import com.irun.pm.utils.StringUtil;
import com.irun.pm.utils.TakePhotoUtils;
import com.irun.pm.utils.Utils;

/**
 * 车辆信息添加页面
 * 
 * @author Administrator
 * 
 */
public class CarAddActivity extends BaseActivity implements OnClickListener {
	private DriverInfoControllers controllers;
	private EditText etCardNum;
	private EditText etDate;
	private EditText etaddress;
	private EditText etResult;
	private EditText etMachineType;
	private EditText etName;
	private EditText etNative;
	private ImageView ivCardPhoto;
	private static final File PHOTO_DIR = new File(
			Environment.getExternalStorageDirectory() + "/DCIM/Camera");
	private static final int REQUES_CAMERA = 0;
	private static final int DIALOG_EXIT = 1;
	private File mCurrentPhotoFile;
	private Context mContext;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.car_add);
		mContext = this;
		findViewById(R.id.btnSaveEdit).setOnClickListener(this);
		controllers = new DriverInfoControllers(this);
		etCardNum = (EditText) findViewById(R.id.etCardNum);
		etDate = (EditText) findViewById(R.id.etDate);
		etDate.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				getDatePickerDialogForDate(etDate);
			}
		});
		etaddress = (EditText) findViewById(R.id.etaddress);
		etMachineType = (EditText) findViewById(R.id.etMachineType);
		etName = (EditText) findViewById(R.id.etName);
		etNative = (EditText) findViewById(R.id.etNative);
		etResult = (EditText) findViewById(R.id.etResult);
		ivCardPhoto = (ImageView) findViewById(R.id.ivCardPhoto);
		ivCardPhoto.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnSaveEdit:
			final String cardNum = etCardNum.getText().toString().trim();
			final String date = etDate.getText().toString().trim();
			final String address = etaddress.getText().toString().trim();
			final String machineType = etMachineType.getText().toString()
					.trim();
			final String name = etName.getText().toString().trim();
			if (StringUtil.isEmpty(cardNum)) {
				etCardNum.setError(Html.fromHtml("<font  color='black'>"
						+ getRstr(R.string.car_input_carnumber) + "</font>"));
				return;
			} else if (StringUtil.isEmpty(date)) {
				etDate.setError(Html.fromHtml("<font  color='black'>"
						+ getRstr(R.string.car_input_date) + "</font>"));
				return;
			} else if (StringUtil.isEmpty(address)) {
				etaddress.setError(Html.fromHtml("<font  color='black'>"
						+ "品牌型号" + "</font>"));
				return;
			} else if (StringUtil.isEmpty(machineType)) {
				etMachineType.setError(Html.fromHtml("<font  color='black'>"
						+ getRstr(R.string.car_input_checkdate) + "</font>"));
				return;
			} else if (StringUtil.isEmpty(name)) {
				etName.setError(Html.fromHtml("<font  color='black'>"
						+ getRstr(R.string.car_input_machinetype) + "</font>"));
				return;
			}
			doProgress("提示", "正在保存中...", new Callable<String>() {
				@Override
				public String call() throws Exception {
					Thread.sleep(2000);
					return null;
				}
			}, new Callback<String>() {
				@Override
				public void onCallback(String pCallbackValue) {
					try {
						DriverInfo driverInfo = new DriverInfo();
						driverInfo.name = name;
						driverInfo.cardNumber = cardNum;
						driverInfo.date = date.replace(" ", "#");;
						driverInfo.card = machineType;
						driverInfo.address = address;
						driverInfo.type = Utils.TYPE_CARINFO_QUERY;
						driverInfo.nativeAddress = etNative.getText().toString();
						driverInfo.result = etResult.getText().toString();
						driverInfo.photoPath = filePath;
						String result = controllers.saveDriver(driverInfo);//.insertDriverInfo(driverInfo, Utils.TYPE_CARINFO_QUERY);
						if (result != null && result.equals("成功")) {
							Toast.makeText(CarAddActivity.this,	"添加成功！", Toast.LENGTH_SHORT).show();
							setResult(RESULT_OK);
							finish();
						} else {
							Toast.makeText(CarAddActivity.this, "添加失败", Toast.LENGTH_SHORT).show();
						}
					} catch (Exception e) {
					}
				}
			}, null);
			break;
		case R.id.ivCardPhoto:
			TakePhotoUtils takePhotoUtils = new TakePhotoUtils(this);
			PHOTO_DIR.mkdirs();
			mCurrentPhotoFile = new File(PHOTO_DIR,
					TakePhotoUtils.getPhotoFileName());
			Intent intent = takePhotoUtils.doTakePhoto(mCurrentPhotoFile);
			startActivityForResult(intent, REQUES_CAMERA);
			break;

		default:
			break;
		}
	}

	String filePath = "";

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_CANCELED) {
			return;
		}
		switch (requestCode) {
		case REQUES_CAMERA:
			Bitmap bmp = ImageUtil.compressHeadBitMap(mCurrentPhotoFile
					.getAbsolutePath());
			filePath = FileUtils.FILE_POLECE_IMAGE
					+ TakePhotoUtils.getPhotoFileName();
			ImageUtil.saveBmp(
					bmp,
					FileUtils.FILE_POLECE_IMAGE
							+ TakePhotoUtils.getPhotoFileName());
			ivCardPhoto.setImageBitmap(bmp);
			break;

		default:
			break;
		}
	}

	@Override
	public void onBackPressed() {
		showDialog(DIALOG_EXIT);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		AlertDialog dialog = null;
		switch (id) {
		case DIALOG_EXIT:
			dialog = new AlertDialog.Builder(this).setTitle("提示")
					.setMessage("是否退出编辑?")
					.setPositiveButton("确定", new Dialog.OnClickListener() {

						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							CarAddActivity.this.finish();
						}
					}).setNegativeButton("取消", null).create();
			break;

		default:
			break;
		}
		return dialog;
	}
	
	/**
	 * 获取日期
	 * @author huangsm
	 * @date 2012-5-26
	 * @email huangsanm@gmail.com
	 * @description
	 */
	private void getDatePickerDialogForDate(final EditText et){
		final Calendar cal = Calendar.getInstance();
		final int y = cal.get(Calendar.YEAR);
		final int mOfy = cal.get(Calendar.MONTH);
		final int dOfm = cal.get(Calendar.DAY_OF_MONTH);
//		final int hourOfDay = cal.get(Calendar.HOUR_OF_DAY);
//		final int minute = cal.get(Calendar.MINUTE);
		final DatePickerDialog dpd = new DatePickerDialog(this, new OnDateSetListener() {
			@Override
			public void onDateSet(DatePicker view, final int year, final int monthOfYear, final int dayOfMonth) {
				et.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
//				new TimePickerDialog(mContext, new TimePickerDialog.OnTimeSetListener() {
//					@Override
//					public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
//						et.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth + " " + hourOfDay + ":" + minute);
//					}
//				}, hourOfDay, minute, true).show();
			}
		}, y, mOfy, dOfm);
		dpd.show();
	}
}
